package com.jinxin.platform.cdacsrecord.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.jinxin.platform.cdacsrecord.core.mapper.JurenAcsControlUserInfoMapper;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.*;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.CommonCodeEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.Constant;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.ResultEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.*;
import com.jinxin.platform.cdacsrecord.core.redis.RedisUtil;
import com.jinxin.platform.cdacsrecord.core.service.AcsControlModuleInvokeService;
import com.jinxin.platform.cdacsrecord.core.service.BaseService;
import com.jinxin.platform.cdacsrecord.core.service.RestTemplateService;
import com.jinxin.platform.cdacsrecord.core.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.io.File;
import java.time.LocalDateTime;
import java.util.*;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2020-07-21
 * @Author: Lingnan
 **/
@Service
@Slf4j
public class RestTemplateServiceImpl extends BaseService implements RestTemplateService {
    @Autowired
    private AcsControlModuleInvokeService invokeService;
//    @Value("${cdacsrecord.account-info.appid}")
//    private String appId;
//    @Value("${cdacsrecord.account-info.appsecret}")
//    private String appsecret;
//    @Value("${cdacsrecord.account-info.phone}")
//    private String phone;
    @Value("${cdacsrecord.url-info.etoToken}")
    private String etoTokenUrl;
    @Value("${cdacsrecord.url-info.common-host}")
    private String commonHost;
    @Value("${cdacsrecord.url-info.listByToken}")
    private String listByTokenUrl;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RestTemplateUtils2 restTemplateUtils2;
    @Autowired
    private JurenAcsControlUserInfoMapper userInfoMapper;

    // 获取授权的 etoToken  2小时过期
    @Override
    public String getEtoToken(boolean isFromRedis) {
        // 如果redis中存在就从redis中取
//        String userInfo = invokeService.getLoginUserInfo();
//        String userAccount = userInfo != null && !userInfo.equals("null") ? JSONObject.parseObject(userInfo).get("userAccount").toString() : "";
//        String tokenKey = "etoToken_"+userAccount;
        String tokenKey = Constant.MODULE_PREX+"etoToken";
        if(redisUtil.hasKey(tokenKey) && isFromRedis){
            String etoToken = (String)redisUtil.get(tokenKey);
            return etoToken;
        }
        AppIdSecretInfo appIdSecretInfo = getAppIdSecretInfo();
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("appId", appIdSecretInfo != null ? appIdSecretInfo.getAppid() : "");
        params.add("appSecret", appIdSecretInfo != null ? appIdSecretInfo.getAppsecret() : "");
        ResultVO resultVO = RestTemplateUtils.sendRequest(etoTokenUrl, params,ResultVO.class,"post");
        if(resultVO != null){
            // success
            if(isSucceed2(resultVO)){
                JSONObject object = JSONObject.parseObject(resultVO.getObject().toString());
                String etoToken = object.getString("etoToken");
                redisUtil.set(tokenKey,etoToken,600L); // 10分钟
                return etoToken;
            }else {
                log.info("getEtoToken fail: " + resultVO.toString());
            }
        }
        return null;
    }

    protected AppIdSecretInfo getAppIdSecretInfo() {
        String key = "appid_secret";
        AppIdSecretInfo appIdSecretInfo = null;
        if(redisUtil.hasKey(key)){
            String jsonStr = (String)redisUtil.get(key);
            appIdSecretInfo = JSONObject.parseObject(jsonStr, AppIdSecretInfo.class);
//            try {
//                appIdSecretInfo = (AppIdSecretInfo) SerializeUtil.deserialize((byte[]) redisUtil.get(key));
//            } catch (IOException e) {
//                e.printStackTrace();
//            } catch (ClassNotFoundException e) {
//                e.printStackTrace();
//            }
        }
        return appIdSecretInfo;
    }

    /**
     * 获取的etoTicket 两小时过期，连续多次请求，仅最后一次结果有效
     * @param companyId 小区id
     * @return
     */
    int index = 0;
    @Override
    public String getEtoTicket(String companyId) {
        if(StringUtils.isEmpty(companyId)){
            return null;
        }
        log.info("第"+ (index++)+ "次获取ticket, 时间是: " + LocalDateTime.now());
//        String userInfo = invokeService.getLoginUserInfo();
//        String userAccount = userInfo != null ? JSONObject.parseObject(userInfo).get("userAccount").toString() : "";
//        String etoTicketKey = "etoTicket_"+companyId + "_"+userAccount;
        // 不从redis中获取
//        String etoTicketKey = Constant.MODULE_PREX + "etoTicket_"+companyId;
//        if(redisUtil.hasKey(etoTicketKey)){
//            return (String)redisUtil.get(etoTicketKey);
//        }
        String etoToken = getEtoToken(false);//不从redis中获取
        if(!StringUtils.isEmpty(etoToken)){
            ResultVO resultVO = getResultVO(etoToken,companyId);
            if(resultVO != null){
                if (!resultVO.getRstId().equals(Constant.ETO_TOKEN_RSTID_SUCCESS)) {
                    // 请求失败getEtoToken不去redis中拿
                    log.info("getEtoTicket fail: " + resultVO.toString());
                    etoToken = getEtoToken(false);
                    resultVO = getResultVO(etoToken, companyId);
                    if (resultVO.getObject() == null) {
                        return null;
                    }
                }
                JSONObject object = JSONObject.parseObject(resultVO.getObject().toString());
                String etoTicket = object.getString("etoTicket");
//                redisUtil.set(etoTicketKey,etoTicket,600L); //115分钟---->10分钟
                return etoTicket;
            }
        }
        return null;
    }

    @Override
    public ResultVO housingEstateOperate(String oper, JurenAcsCommunityInfo communityInfo) {
        if(Constant.OPERATION_SIGN_EDIT.equals(oper) || Constant.OPERATION_SIGN_DEL.equals(oper)){
            if(StringUtils.isEmpty(communityInfo.getCompanyId())){
                return new ResultVO(0,"修改或删除小区id不能为空",null, false, null);
            }
        }
        MultiValueMap<String, Object> params = Utils.transBean2Map(communityInfo);
        String etoToken = getEtoToken(true);
        //String userInfo = invokeService.getLoginUserInfo();
        //String userAccount = userInfo != null && !userInfo.equals("null") ? JSONObject.parseObject(userInfo).get("userAccount").toString() : "";
        AppIdSecretInfo appIdSecretInfo = getAppIdSecretInfo();
        params.add("etoToken", etoToken);
        params.add("phone", appIdSecretInfo != null ? appIdSecretInfo.getPhone() : "");
        params.add("oper", oper);
        params.remove("remark");
        String housingUrl = commonHost + "/housingEstate/operate.do";
        ResultVO response = RestTemplateUtils.sendRequest(housingUrl, params,ResultVO.class,"post");
        if(response != null){
            if(Constant.ETO_TOKEN_RSTID_SUCCESS.equals(response.getRstId())){
                return response;
            }else {
                log.info("housingEstateOperate: "+oper+" fail: " + response.toString());
                params.remove("etoToken");
                params.add("etoToken", getEtoToken(false));
                response = RestTemplateUtils.sendRequest(housingUrl, params, ResultVO.class, "post");
                return response;
            }
        }
        return null;
    }

    @Override
    public ResultVO2 buildingblockOperate(String oper, AcsControlBlockInfoDO blockInfoDO) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        String companyId = blockInfoDO.getCompanyId();
        if(StringUtils.isEmpty(companyId)){
            return new ResultVO2(0,"小区id不能为空",null, false, null);
        }
        String housingEstateId = blockInfoDO.getHousingEstateId();
        if(StringUtils.isEmpty(housingEstateId)){
            return new ResultVO2(0,"小区编号不能为空",null, false, null);
        }
        if(Constant.OPERATION_SIGN_EDIT.equals(oper) || Constant.OPERATION_SIGN_DEL.equals(oper)){
            String blockId = blockInfoDO.getBlockId();
            if(StringUtils.isEmpty(blockId)){
                return new ResultVO2(0,"修改或删除楼栋id不能为空",null, false, null);
            }
            params.add("id", blockId);
        }
        String etoTicket = getEtoTicket(companyId);
        params.add("etoTicket", etoTicket);
        params.add("oper", oper);
        if(!Constant.OPERATION_SIGN_DEL.equals(oper)){
            params.add("blockName", blockInfoDO.getBlockName());
            params.add("blockNo", blockInfoDO.getBlockNo());
            params.add("blockType", blockInfoDO.getBlockType());
        }
        params.add("housingEstateId", housingEstateId);// 小区编号
        params.add("companyId", companyId);
        params.remove("remark");
        String bloackUrl = commonHost + "/buildingblock/operate.do";
        ResultVO2 response = RestTemplateUtils.sendRequest(bloackUrl, params,ResultVO2.class,"post");
        if(response != null){
//            JSONObject jsonObject = JSONObject.parseObject(response.toString());
            if(Constant.ETO_TOKEN_RSTID_SUCCESS.equals(response.getRstId())){
                return response;
            }else {
                log.info("buildingblockOperate: "+oper+" fail: " + response.toString());
                response = RestTemplateUtils.sendRequest(bloackUrl, params, ResultVO2.class, "post");
                return response;
            }
        }
        return null;
    }

    @Override
    public ResultVO2 buildingunitOperate(String oper, AcsControlRoomInfoDO roomInfoDO) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        String companyId = roomInfoDO.getCompanyId();
        if(StringUtils.isEmpty(companyId)){
            return new ResultVO2(0,"小区id不能为空",null, false, null);
        }
        String housingEstateId = roomInfoDO.getHousingEstateId();
        if(StringUtils.isEmpty(housingEstateId)){
            return new ResultVO2(0,"小区编号不能为空",null, false, null);
        }
        if(Constant.OPERATION_SIGN_EDIT.equals(oper) || Constant.OPERATION_SIGN_DEL.equals(oper)){
            String roomId = roomInfoDO.getRoomId();
            if(StringUtils.isEmpty(roomId)){
                return new ResultVO2(0,"修改或删除房间,id不能为空",null, false, null);
            }
            params.add("id", roomId);
        }
        String etoTicket = getEtoTicket(companyId);
        params.add("etoTicket", etoTicket);
        params.add("oper", oper);
        if(!Constant.OPERATION_SIGN_DEL.equals(oper)){
            params.add("unitName", roomInfoDO.getRoomName());
        }
        params.add("buildingBlockId", roomInfoDO.getBlockId());
        params.add("housingEstateId", housingEstateId);// 小区编号
        params.add("companyId", companyId);
        String bloackUrl = commonHost + "/buildingunit/operate.do";
        ResultVO2 response = RestTemplateUtils.sendRequest(bloackUrl, params,ResultVO2.class,"post");
        if(response != null){
//            JSONObject jsonObject = JSONObject.parseObject(response.toString());
            if(Constant.ETO_TOKEN_RSTID_SUCCESS.equals(response.getRstId())){
                return response;
            }else {
                log.info("buildingunitOperate: "+oper+" fail: " + response.toString());
                response = RestTemplateUtils.sendRequest(bloackUrl, params, ResultVO2.class, "post");
                return response;
            }
        }
        return null;
    }

    @Override
    public ResultVO2 wyOwnerYcOperate(String oper, AcsControlUserInfoDO userInfoDO) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        String userId = userInfoDO.getUserId();
        String blockId = userInfoDO.getUserBlockId();
        String roomNo = userInfoDO.getUserRoomName();
        if (!StringUtils.isEmpty(roomNo) && roomNo.contains("-")){ // 如果是**栋**单元-601格式的只取-后面
            roomNo = roomNo.split("-")[1];
        }
        String fafId = userInfoDO.getUserFingerprint();
        if(Constant.OPERATION_SIGN_EDIT.equals(oper) || Constant.OPERATION_SIGN_DEL.equals(oper)){
            if(StringUtils.isEmpty(userId)){
                return new ResultVO2(0,"修改或删除人员,id不能为空",null, false, null);
            }
            params.add("id", userId);
            if(!StringUtils.isEmpty(fafId)){
                params.add("fafId", fafId);
            }
        }
        if(!Constant.OPERATION_SIGN_DEL.equals(oper)){
            if(StringUtils.isEmpty(blockId)){
                return new ResultVO2(0,"增加或修改人员,楼栋id不能为空",null, false, null);
            }
            if(StringUtils.isEmpty(roomNo)){
                return new ResultVO2(0,"增加或修改人员,房间号不能为空",null, false, null);
            }
        }
        String etoTicket = getEtoTicket(userInfoDO.getCompanyId());
        params.add("etoTicket", etoTicket);
        params.add("oper", oper);
        if(!Constant.OPERATION_SIGN_DEL.equals(oper)){
            params.add("name", userInfoDO.getUserName());
            params.add("phone", userInfoDO.getUserPhone());
            params.add("gender", userInfoDO.getGender());
            params.add("areaId", blockId);
            params.add("roomNo", roomNo);//这里是房间编号，不是房间id
            params.add("userType", userInfoDO.getUserType());
            params.add("idCardNo", userInfoDO.getUserCard());
        }
        String userUrl = commonHost + "/wyOwnerYc/operate.do";
        ResultVO2 response = RestTemplateUtils.sendRequest(userUrl, params,ResultVO2.class,"post");
        if(response != null){
//            JSONObject jsonObject = JSONObject.parseObject(response.toString());
            if(Constant.ETO_TOKEN_RSTID_SUCCESS.equals(response.getRstId())){
                return response;
            }else {
                log.info("wyOwnerYcOperate: "+oper+" fail: " + response.toString());
                response = RestTemplateUtils.sendRequest(userUrl, params, ResultVO2.class, "post");
                return response;
            }
        }
        return null;
    }

    @Override
    public ResultVO2 extractFileFaceFeature(String oper,File faceImg, String companyId, String userId,String fafId) {
        if(StringUtils.isEmpty(faceImg)){
            return new ResultVO2(0,"人脸照片不存在",null, false, null);
        }
        if(StringUtils.isEmpty(companyId)){
            return new ResultVO2(0,"小区不存在",null, false, null);
        }
        if(StringUtils.isEmpty(userId)){
            return new ResultVO2(0,"用户id不存在",null, false, null);
        }
        Map<String, Object> params = new HashMap<>();
        if(Constant.OPERATION_SIGN_EDIT.equals(oper) || Constant.OPERATION_SIGN_DEL.equals(oper)){
            if(StringUtils.isEmpty(fafId)){
                return new ResultVO2(0,"修改或删除人脸照片,人脸照片id不能为空",null, false, null);
            }
            params.put("fafId", fafId);
        }
        String faceUrl = commonHost + "/face/extractFileFaceFeature.do";
        String etoTicket = getEtoTicket(companyId);
        params.put("etoTicket", etoTicket);
        params.put("companyId", companyId);
        params.put("userId", userId);
        params.put("userType", 2); //1：物业人员2：住户
        params.put("file", new FileSystemResource(faceImg));

        ResultVO2 jsonResult = restTemplateUtils2.httpPostFrom(faceUrl, params, null, ResultVO2.class);
        if(jsonResult != null){
            return JSON.parseObject(toJSONString(jsonResult), ResultVO2.class);
        }
        return null;
    }

    @Override
    public ResultVO2 removeFases(String companyId, String fafId) {
        if(StringUtils.isEmpty(companyId)){
            return new ResultVO2(0,"小区不存在",null, false, null);
        }
        if(StringUtils.isEmpty(fafId)){
            return new ResultVO2(0,"人脸照片id不存在",null, false, null);
        }
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        String faceUrl = commonHost + "/face/removeFases.do";
        String etoTicket = getEtoTicket(companyId);
        params.add("etoTicket", etoTicket);
        params.add("companyId", companyId);
        params.add("fafIds[]", fafId);
        params.add("userType", 2); //1：物业人员2：住户
        ResultVO2 jsonResult = RestTemplateUtils.sendRequest(faceUrl, params,ResultVO2.class,"get");
        if(jsonResult != null){
            return JSON.parseObject(toJSONString(jsonResult), ResultVO2.class);
        }
        return null;
    }

    @Override
    public String[] queryFaces(String companyId, String userId) {
        if(StringUtils.isEmpty(companyId) || StringUtils.isEmpty(userId)){
            return null;
        }
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        String faceUrl = commonHost + "/face/queryFaces.do";
        String etoTicket = getEtoTicket(companyId);
        params.add("etoTicket", etoTicket);
        params.add("companyId", companyId);
        params.add("userId", userId);
        params.add("userType", 2);
        ResultVO3 jsonResult = RestTemplateUtils.sendRequest(faceUrl, params,ResultVO3.class,"post");
        if(jsonResult != null && Constant.ETO_TOKEN_RSTID_SUCCESS.equals(jsonResult.getRstId())){
            JSONArray jsonArray = jsonResult.getObject();
            if(jsonArray != null && jsonArray.size() > 0){
                String[] result = new String[2];
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                result[0] = jsonObject.getString("fafId");
                result[1] = jsonObject.getString("imgPath");
                return result;
            }
            return null;
        }
        return null;
    }

    @Override
    public ResultVO2 wyOwnerOperate(String oper, AcsControlUserInfoDO userInfoDO) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        String userId = userInfoDO.getUserId();
        String blockId = userInfoDO.getUserBlockId();
        if(Constant.OPERATION_SIGN_EDIT.equals(oper) || Constant.OPERATION_SIGN_DEL.equals(oper)){
            if(StringUtils.isEmpty(userId)){
                return new ResultVO2(0,"修改或删除人员,id不能为空",null, false, null);
            }

            params.add("id", userId);
        }
        String etoTicket = getEtoTicket(userInfoDO.getCompanyId());
        params.add("etoTicket", etoTicket);
        params.add("oper", oper);
        if(!Constant.OPERATION_SIGN_DEL.equals(oper)){
            params.add("areaId", blockId);
            params.add("companyId", userInfoDO.getCompanyId());
            params.add("phone", userInfoDO.getUserPhone());
            params.add("name", userInfoDO.getUserName());
            params.add("userType", Integer.valueOf(userInfoDO.getUserType()));
            params.add("parentId", userInfoDO.getParentId());
            params.add("spTag", userInfoDO.getState());//审核通过
            params.add("gender", userInfoDO.getGender());
            params.add("idCardNo", userInfoDO.getUserCard());
        }
        String userUrl = commonHost + "/wyOwner/submit.do";
        ResultVO2 response = RestTemplateUtils.sendRequest(userUrl, params,ResultVO2.class,"post");
        if(response != null && Constant.ETO_TOKEN_RSTID_SUCCESS.equals(response.getRstId())){
            return response;
        }else {
            log.info("wyOwnerOperate: "+oper+" fail: " + response.toString());
            response = RestTemplateUtils.sendRequest(userUrl, params, ResultVO2.class, "post");
            return response;
        }
    }

    @Override
    public ResultVO2 iCCardSubmit(String oper, JurenIcCardInfo icCardInfo) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        String userId = icCardInfo.getUserId();
        String companyId = icCardInfo.getCompanyId();
        if(StringUtils.isEmpty(userId)){
            return new ResultVO2(0,"业主id不能为空",null, false, null);
        }
        params.add("userId", userId);
        if(StringUtils.isEmpty(companyId)){
            return new ResultVO2(0,"小区id不能为空",null, false, null);
        }
        params.add("companyId", companyId);
        Integer userType = StringUtils.isEmpty(icCardInfo.getUserType()) ? null : icCardInfo.getUserType();
        String identifier = icCardInfo.getIdentifier();
        String cardNO = icCardInfo.getCardNO();
        String time = icCardInfo.getTime();
        if(!Constant.OPERATION_SIGN_DEL.equals(oper)){
            if(StringUtils.isEmpty(userType)){
                return new ResultVO2(0,"用户类型不能为空",null, false, null);
            }
            params.add("userType", userType);
            if(StringUtils.isEmpty(identifier)){
                return new ResultVO2(0,"卡编号不能为空",null, false, null);
            }
            params.add("identifier", identifier);
            if(StringUtils.isEmpty(cardNO)){
                return new ResultVO2(0,"卡号不能为空",null, false, null);
            }
            params.add("cardNO", cardNO);
            if(StringUtils.isEmpty(time)){
                return new ResultVO2(0,"有效时间不能为空",null, false, null);
            }
            params.add("time", time);
        }
        String cardId = icCardInfo.getCardId();
        if(Constant.OPERATION_SIGN_EDIT.equals(oper)){
            if(StringUtils.isEmpty(cardId)){
                return new ResultVO2(0,"卡号id不能为空",null, false, null);
            }
            params.add("id", cardId);

        }
        String etoTicket = getEtoTicket(companyId);
        params.add("etoTicket", etoTicket);
        params.add("oper", oper);
        String userUrl = commonHost + "/ICCard/submit.do";
        ResultVO2 response = RestTemplateUtils.sendRequest(userUrl, params,ResultVO2.class,"post");
        if(response != null){
//            JSONObject jsonObject = JSONObject.parseObject(response.toString());
            if(Constant.ETO_TOKEN_RSTID_SUCCESS.equals(response.getRstId())){
                return response;
            }else {
                log.info("iCCardSubmit: "+oper+" fail: " + response.toString());
                response = RestTemplateUtils.sendRequest(userUrl, params, ResultVO2.class, "post");
                return response;
            }
        }
        return null;
    }

    @Override
    public ResultEntity listAllCard(Integer page, Integer rows, JurenIcCardInfo icCardInfo) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        Integer userType = StringUtils.isEmpty(icCardInfo.getUserType()) ? null : icCardInfo.getUserType();
        String userId = icCardInfo.getUserId();
        String companyId = icCardInfo.getCompanyId();
        if(StringUtils.isEmpty(userType)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"用户类型不能为空","");
        }
        params.add("userType", userType);
        if(StringUtils.isEmpty(userId)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"用户id不能为空","");
        }
        params.add("userId", userId);
        if(StringUtils.isEmpty(companyId)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"小区id不能为空","");
        }
        params.add("rows", rows);
        params.add("page", page);
        params.add("companyId", companyId);
        String etoTicket = getEtoTicket(companyId);
        params.add("etoTicket", etoTicket);
        String userUrl = commonHost + "/ICCard/listAllCard.do";
        ResultVO response = RestTemplateUtils.sendRequest(userUrl, params,ResultVO.class,"get");
        if(response != null &&  Constant.ETO_TOKEN_RSTID_SUCCESS.equals(response.getRstId())){
            JSONObject jsonObject = response.getObject();
            if(jsonObject != null){
                DataResult dataResult = JSON.parseObject(toJSONString(jsonObject), DataResult.class);
                return new ResultEntity(CommonCodeEntity.SUC_CODE,"success",dataResult);
            }
        }
        return null;
    }

    @Override
    public ResultEntity buildingunitSearch(Integer page, Integer rows, String parentId, String companyId) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        if(StringUtils.isEmpty(parentId)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"楼栋id不能为空","");
        }
        if(StringUtils.isEmpty(companyId)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"小区id不能为空","");
        }
        params.add("rows", rows);
        params.add("page", page);
        params.add("parentId", parentId);
        params.add("companyId", companyId);
        String etoTicket = getEtoTicket(companyId);
        params.add("etoTicket", etoTicket);
        String userUrl = commonHost + "/buildingunit/search4Pages.do";
        DataResult2 response = RestTemplateUtils.sendRequest(userUrl, params,DataResult2.class,"get");
        if(response != null && response.getRecords() > 0){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"success",response);
        }
        return null;
    }

    @Override
    public ResultEntity getCommunities(Integer bopType) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        if(StringUtils.isEmpty(bopType)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"服务类型不能为空","");
        }
        String etoToken = getEtoToken(true);
        params.add("bopType", bopType);
        params.add("etoToken", etoToken);
        CommunityDataResult response = RestTemplateUtils.sendRequest(listByTokenUrl, params,CommunityDataResult.class,"get");
        if(response != null && response.getObject() != null && response.getObject().size() > 0){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"success",response);
        }
        return null;
    }

    @Override
    public ResultEntity wyOwnerYcSearch(Integer page, Integer rows, String companyId) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        if(StringUtils.isEmpty(companyId)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"小区id不能为空","");
        }
        params.add("rows", rows);
        params.add("page", page);
//        params.add("areaId", areaId);
        String etoTicket = getEtoTicket(companyId);
        params.add("etoTicket", etoTicket);
        String userUrl = commonHost + "/wyOwnerYc/search4Pages.do";
        DataResult2 response = RestTemplateUtils.sendRequest(userUrl, params,DataResult2.class,"get");
        if(response != null && response.getRecords() > 0){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"success",response);
        }
        return null;
    }

    @Override
    public List<AcsControlUserInfoDO> listMemebersById(String parentId, String companyId) {
        List<AcsControlUserInfoDO> list = new ArrayList<>();
        if(StringUtils.isEmpty(parentId) || StringUtils.isEmpty(companyId)){return list;}
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        String etoTicket = getEtoTicket(companyId);
        params.add("etoTicket", etoTicket);
        params.add("page", 1); // 默认
        params.add("rows", 20);// 默认10，一般家庭成员也就几个
        params.add("parentId", parentId);
        params.add("companyId", companyId);
        params.add("userType", 12); // 12：家庭成员
        String memeberUrl = commonHost + "/wyOwner/listAll.do";
        DataResult2 response = RestTemplateUtils.sendRequest(memeberUrl, params,DataResult2.class,"get");
        if(response != null && response.getRecords() > 0){
            JSONArray jsonArray = response.getRows();
            if(jsonArray != null){
                for(int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    AcsControlUserInfoDO memeber = new AcsControlUserInfoDO();
                    String userId = jsonObject.getInteger("oId")+"";
                    memeber.setUserId(userId);
                    memeber.setUserName(jsonObject.getString("name"));
                    memeber.setUserCardType("1");
                    memeber.setUserCard(jsonObject.getString("idCardNo"));
                    String userPhone = !StringUtils.isEmpty(jsonObject.getString("phone")) ? jsonObject.getString("phone") : "-";
                    memeber.setUserPhone(userPhone);
                    JSONObject areaJson = jsonObject.getJSONObject("buildingArea");
                    if(areaJson != null){
                        memeber.setUserBlockId(areaJson.getInteger("areaId")+"");
                        memeber.setUserBlockName(areaJson.getString("areaName"));
                    }
                    memeber.setUserRoomId(jsonObject.getInteger("unitAreaId")+"");
                    memeber.setUserRoomName(jsonObject.getString("roomNo"));
                    memeber.setCreateTime(DateUtil.getDateTimeOfTimestamp(jsonObject.getLong("createTime")));
                    memeber.setGender(jsonObject.getInteger("gender"));
                    memeber.setUserType(jsonObject.getInteger("userType")+"");
                    memeber.setParentId(jsonObject.getInteger("parentId")+"");
                    memeber.setState(jsonObject.getInteger("spTag")+"");
                    memeber.setHushaiConsistent(0);//默认0人户一致
                    memeber.setPartyMembership(1);//默认1群众
                    memeber.setCompanyId(companyId);
                    // TODO 暂时去掉人脸同步
                    try {
                        String[] idPathArr = queryFaces(companyId, userId);
                        if(idPathArr != null){
                            memeber.setUserFingerprint(idPathArr[0]);
                            memeber.setUserFaceInfo(idPathArr[1]);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    list.add(memeber);
                    AcsControlUserInfoDO UserInfoDO = userInfoMapper.selById(userId);
                    if(UserInfoDO == null){
                        userInfoMapper.insert(memeber);
                    }else {
                        userInfoMapper.updateByPrimaryKey(memeber);
                    }
                }
            }
        }
        return list;
    }

    @Override
    public ResultEntity listDoorDevices(DeviceParam param,String companyId) {
        Map<String, String> params = Utils.transformBean2Map(param);
        String etoTicket = getEtoTicket(companyId);
        params.put("etoTicket", etoTicket);
        if(StringUtils.isEmpty(etoTicket)){
            return new ResultEntity(CommonCodeEntity.FAIL,"获取etoTicket失败，请联系管理员","");
        }
        if(!StringUtils.isEmpty(param.getLockIds())){
            params.put("lockIds[]",param.getLockIds());
        }
        if(StringUtils.isEmpty(param.getSearchString())){
            params.remove("searchField");
        }
        String url = commonHost + "/gateLock/search4Pages.do";
        DataResult2 response = null;
        try {
            HttpClientResult clientResult = HttpClientPoolUtil.doGet(url, params, false);
            if(clientResult != null && Constant.REQUEST_STATUS_SUCCEED.equals(clientResult.getCode())){
                response = JSON.parseObject(clientResult.getContent(), DataResult2.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(response != null){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"success",response);
        }
        return new ResultEntity(CommonCodeEntity.FAIL,"fail",response);
    }

    @Override
    public ResultEntity listOpenRecord(OpenRecordParam param,String companyId) {
        Map<String, String> params = Utils.transformBean2Map(param);
        String etoTicket = getEtoTicket(companyId);
        if(StringUtils.isEmpty(etoTicket)){
            return new ResultEntity(CommonCodeEntity.FAIL,"获取etoTicket失败，请联系管理员","");
        }
        params.put("etoTicket", etoTicket);
        params.put("sidx", "createTime");
        params.put("sord", "desc");
        // timeTag 为1 启用后用startTime和endTime  dateTag启用后用startDate和endDate
        params.put("startTime", param.getStartDate());
        params.put("endTime", param.getEndDate());
        params.put("timeTag", "1");
        if(!StringUtils.isEmpty(param.getAreaIds())){
            params.put("areaIds[]",param.getAreaIds());
        }
        if(StringUtils.isEmpty(param.getSearchString())){
            params.remove("searchField");
        }
//        MultiValueMap<String, Object> params = Utils.transBean2Map(param);
//        String etoTicket = getEtoTicket();
//        params.add("etoTicket", etoTicket);
//        if(!StringUtils.isEmpty(param.getAreaIds())){
//            params.add("areaIds[]",param.getAreaIds());
//        }
//        if(StringUtils.isEmpty(param.getSearchString())){
//            params.remove("searchField");
//        }
        String url = commonHost + "/gateLockLog/search4Pages.do";
        DataResult2 response = null;
        try {
            HttpClientResult clientResult = HttpClientPoolUtil.doGet(url, params, false);
            log.info("请求返回：" + clientResult.getContent());
            if(clientResult != null && Constant.REQUEST_STATUS_SUCCEED.equals(clientResult.getCode())){
                response = JSON.parseObject(clientResult.getContent(), DataResult2.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultEntity(CommonCodeEntity.FAIL,"获取门禁记录失败","");
        }
//        DataResult2 response = RestTemplateUtils.sendRequest(url, params,DataResult2.class,"get");
        if(response != null){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"success",response);
        }
        log.info("请求失败参数：" + JSON.toJSONString(params));
        return new ResultEntity(CommonCodeEntity.FAIL,"获取门禁记录失败","");
    }

    @Override
    public ResultEntity listCaptureRecord(CaptureRecordParam param,String companyId) {
        if(StringUtils.isEmpty(companyId)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"小区不存在","");
        }
        Map<String, String> params = Utils.transformBean2Map(param);
        String etoTicket = getEtoTicket(companyId);
        if(StringUtils.isEmpty(etoTicket)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"获取etoTicket失败","");
        }
        params.put("etoTicket", etoTicket);
        params.put("sidx", "createTime");
        params.put("sord", "desc");
        params.put("startDate", param.getStartDate());
        params.put("endDate", param.getEndDate());
        if(!StringUtils.isEmpty(param.getAreaIds())){
            params.put("areaIds[]",param.getAreaIds());
        }
        String url = commonHost + "/gateLockLog/capturePedestrian/search4Pages.do";
        DataResult2 response = null;
        try {
            HttpClientResult clientResult = HttpClientPoolUtil.doGet(url, params, false);
            if(clientResult != null && Constant.REQUEST_STATUS_SUCCEED.equals(clientResult.getCode())){
                response = JSON.parseObject(clientResult.getContent(), DataResult2.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultEntity(CommonCodeEntity.FAIL,"fail",response);
        }
        if(response != null){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"success",response);
        }
        return new ResultEntity(CommonCodeEntity.FAIL,"fail",response);
    }

    @Override
    public ResultEntity listBuildingAreaTree(String companyId) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        String etoTicket = getEtoTicket(companyId);
        params.add("etoTicket", etoTicket);
        String userUrl = commonHost + "/buildingArea/treeview.do";
        if(StringUtils.isEmpty(etoTicket)){
            return new ResultEntity(CommonCodeEntity.FAIL,"获取etoTicket失败，请联系管理员",null);
        }
        JSONArray response = RestTemplateUtils.sendRequest(userUrl, params, JSONArray.class,"get");
        if(response != null){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"success",response);
        }
        return new ResultEntity(CommonCodeEntity.FAIL,"fail",response);
    }

    @Override
    public ResultEntity initGateLock(GateLockInfo gateLockInfo,String companyId) {
        MultiValueMap<String, Object> params = Utils.transBean2Map(gateLockInfo);
        String etoTicket = getEtoTicket(companyId);
        params.add("etoTicket", etoTicket);
        String url = commonHost + "/gateLock/init.do";
        ResultVO2 response = RestTemplateUtils.sendRequest(url, params, ResultVO2.class, "post");
        if(response != null && isSucceed(response)){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"success",response);
        }
        assert response != null;
        return new ResultEntity(CommonCodeEntity.FAIL,response.getRstDesc(), response);
    }

    @Override
    public ResultEntity cardStatus(JurenIcCardInfo icCardInfo) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        if(icCardInfo == null){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"参数异常，提交失败","" );
        }
        String cardId = icCardInfo.getCardId();
        String companyId = icCardInfo.getCompanyId();
        Integer state = icCardInfo.getCardState();
        if(StringUtils.isEmpty(cardId)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"IC卡id为空，提交失败","" );
        }
        params.add("cardId",cardId);
        if(StringUtils.isEmpty(companyId)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"小区id为空，提交失败","" );
        }
        params.add("companyId",companyId);
        if(StringUtils.isEmpty(state)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"卡状态为空，提交失败","" );
        }
        params.add("cardState",state);
        String etoTicket = getEtoTicket(companyId);
        params.add("etoTicket", etoTicket);
        String userUrl = commonHost + "/ICCard/cardStatus.do";
        ResultVO2 response = RestTemplateUtils.sendRequest(userUrl, params,ResultVO2.class,"get");
        if(isSucceed(response)){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"操作成功","success");
        }else {
            assert response != null;
            return new ResultEntity(CommonCodeEntity.FAIL,response.getRstDesc(),"fail");
        }
    }

    private ResultVO getResultVO(String etoToken,String companyId) {
        AppIdSecretInfo appIdSecretInfo = getAppIdSecretInfo();
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("etoToken", etoToken);
        params.add("phone", appIdSecretInfo != null ? appIdSecretInfo.getPhone() : "");
        params.add("companyId", companyId);
        String authLoginUrl = commonHost + "/etoTokenLogin/authLogin.do";
        return RestTemplateUtils.sendRequest(authLoginUrl, params,ResultVO.class,"post");
    }

    @Override
    public ResultEntity getAreaTree() {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        String etoToken = getEtoToken(true);
        params.add("etoToken", etoToken);
        String areaUrl = commonHost + "/housingEstate/getAreaTree.do";
        ResultVO3 response = RestTemplateUtils.sendRequest(areaUrl, params,ResultVO3.class,"get");
        if(isSucceed3(response)){
            JSONArray dataResult = response.getObject();
            JSONArray returnResult = new JSONArray();
            for (int i = 0; i < dataResult.size(); i++) {
                JSONObject jsonObject = dataResult.getJSONObject(i);
                AreaInfo areaInfo = JSON.parseObject(toJSONString(jsonObject), AreaInfo.class);
                if(areaInfo != null){
                    JSONObject newObject = new JSONObject();
                    newObject.put("name", areaInfo.getName());
                    newObject.put("value", areaInfo.getId());
                    // 第二级
                    JSONArray children2 = areaInfo.getChildren();
                    if(children2 == null || children2.size() == 0){
                        returnResult.add(newObject);
                        continue;
                    }
                    newObject.put("disabled", true);
                    JSONArray nchildren2 = new JSONArray();
                    for (Iterator iterator = children2.iterator(); iterator.hasNext();) {
                        JSONObject json2 = (JSONObject)iterator.next();
                        AreaInfo areaInfo2 = JSON.parseObject(toJSONString(json2), AreaInfo.class);
                        JSONObject newObject2 = new JSONObject();
                        newObject2.put("name", areaInfo2.getName());
                        newObject2.put("value", areaInfo2.getId());
                        // 第三级
                        JSONArray children3 = areaInfo2.getChildren();
                        if(children3 == null || children3.size() == 0){
                            nchildren2.add(newObject2);
                            continue;
                        }
                        newObject2.put("disabled", true);
                        JSONArray nchildren3 = new JSONArray();
                        for (Iterator iterator2 = children3.iterator(); iterator2.hasNext();) {
                            JSONObject json3 = (JSONObject)iterator2.next();
                            AreaInfo2 areaInfo3 = JSON.parseObject(toJSONString(json3), AreaInfo2.class);
                            JSONObject newObject3 = new JSONObject();
                            newObject3.put("name", areaInfo3.getName());
                            newObject3.put("value", areaInfo3.getId());
                            nchildren3.add(newObject3);
                            newObject2.put("children",nchildren3);
                        }
                        nchildren2.add(newObject2);
                    }
                    newObject.put("children", nchildren2);
                    returnResult.add(newObject);
                }
            }
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"success",returnResult);
        }
        return null;
    }
}
